/*
 键值对（“key = value”）字符串，在开发中经常使用
	要求1：请自己定义一个接口，实现根据key获取.
	要求2：编写测试用例。
	要求3：键值对中间可能有n多空格，请去除空格

	注意：键值对字符串格式可能如下：
	"key1 = value1"
	"key2 =       value2"
	"key3  = value3"
	"key4        = value4"
	"key5   =   "
	"key6   ="
	
	int getKeyByValue(char *keyvaluebuf,  char *keybuf,  char *valuebuf, int * valuebuflen);

	int main(void)
	{
		//...
		getKeyByValude("key1 =   valude1", "key1", buf, &len);
		//...

		return 0;
	}
 */
# include<stdio.h>
# include<string.h>
# include<ctype.h>
int trimspace (char *inbuf,char *outbuf)
{
    if (inbuf == NULL)
        return -4;
    char *tmp = inbuf;
    int begin = 0;
    int end = strlen(inbuf) -1;
    while(isspace(tmp[begin]) && tmp[begin] != 0)
    {
        begin ++;
    }
    while (isspace(tmp[end]) && tmp[end] > 0)
    {
        end --;
    }
    if (tmp[end] == 0)
    {
        return -5;
    }
    int len = end -begin +1;
    strncpy(outbuf ,tmp+begin ,len);
    outbuf[len+1] = 0;//在后面补上结束符0
    return 0;
}
int getKeyByValue(char *keyvaluebuf,  char *keybuf,  char *valuebuf, int * valuebuflen)
{
    //判断这些值是否为空,返回-1
    if (keyvaluebuf == NULL || keybuf == NULL || valuebuf == NULL || valuebuflen == NULL )
        return -1;
    
    //判断是否有要查找的key ,返回-2
    char *p = NULL;
    if ((p = strstr(keyvaluebuf ,keybuf)) == 0)
        return -2;
    
    //判断等号
    char *q;
    p += strlen(keybuf);
    if ((q = strstr(p ,"=")) == 0)
        return -3;
    q += 1;
   printf ("%s",q);
    //调用trimspace函数
    int ret;

    ret = trimspace(q,valuebuf);
    if (ret != 0)
    {
        printf ("trimspce err:%d\n",ret);
        return ret;
    }
    //printf ("\n%s",valuebuf);
    *valuebuf = strlen(valuebuf);
    return 0;
}
int main (void)
{
    char arr[] = "key6   =";
    char key[50] = "key6";
    int len = 0;
    char buf[100] = {0};
    int ret = 0;
    ret = getKeyByValue(arr,key,buf,&len);
    if (ret != 0)
    {
        printf ("getKeyByValue err:%d\n",ret);
        return ret;
    }
    else
    {
        printf ("\n");
        printf ("%s",buf);
        printf ("\n键值的长度为%d\n",strlen(buf));//why?传过来会变少一个
    }
    return 0;
}
